package top.szhome.framework.starter.db.support;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import top.szhome.framework.core.tools.exception.SzhomeException;
import top.szhome.framework.core.tools.support.BaseConverter;
import top.szhome.framework.core.tools.support.Pagination;
import top.szhome.framework.starter.db.wrapper.AutoQueryWrapper;

import java.util.List;

/**
 * 简单服务实现
 *
 * @author 唐加利
 * @date 2023/7/27
 **/
@Slf4j
public class SimpleServiceImpl<M extends BaseMapper<T>, C extends BaseConverter<D, T, V>, D, T extends BaseEntity, V> extends BaseServiceImpl<M, T> implements SimpleService<C, D, T, V>{

    @Autowired
    private C baseConvert;

    @Override
    public C getBaseConvert() {
        return baseConvert;
    }

    @Override
    public Long insert(D req) {
        T entity = getBaseConvert().from(req);
        try {
            getBaseMapper().insert(entity);
            return entity.getId();
        } catch (DuplicateKeyException e) {
            log.error("新增数据失败，违反唯一索引, req={}", req, e);
            throw new SzhomeException("500", "新增数据失败，违反唯一索引");
        }
    }

    @Override
    public Boolean update(D req) {
        T entity = getBaseConvert().from(req);
        try {
            return getBaseMapper().updateById(entity) > 0;
        } catch (DuplicateKeyException e) {
            log.error("更新数据失败，违反唯一索引， req={}", req, e);
            throw new SzhomeException("500", "修改数据失败，违反唯一索引");
        }
    }

    @Override
    public Boolean delete(List<Long> ids) {
        return getBaseMapper().deleteBatchIds(ids) > 0;
    }

    @Override
    public V get(Long id) {
        T user = getBaseMapper().selectById(id);
        return getBaseConvert().to(user);
    }

    @Override
    public List<V> list(Object query) {
        List<T> list = getBaseMapper().selectList(new AutoQueryWrapper<>(query));
        return getBaseConvert().to(list);
    }

    @Override
    public Pagination<V> page(Object query, Page page) {
        Page<T> result = getBaseMapper().selectPage(page, new AutoQueryWrapper<>(query));
        List<V> voList = getBaseConvert().to(result.getRecords());
        Pagination<V> p = new Pagination<>();
        p.setPageSize(result.getSize());
        p.setCurrent(result.getCurrent());
        p.setTotal(result.getTotal());
        p.setData(voList);
        return p;
    }

}
